import { ChangeDetectorRef, Component, ElementRef, Inject, OnInit, ViewChild } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { differenceInSeconds } from 'date-fns';
import { NzMessageService, NzModalService, NzUploadFile } from 'ng-zorro-antd';
import { ossUri, qiniuUri, VOD_CATEGORY_COVER_UPLAOD, VOD_CATEGORY_DELETE, VOD_CATEGORY_INFO, VOD_CATEGORY_SAVE, VOD_DELETE, VOD_LOGO_UPLOAD, VOD_PAGE, VOD_SAVE, VOD_UPLOAD_KEY } from 'src/app/service/action_type';
import { OprationService } from 'src/app/service/opration.service';
import { RequestService } from 'src/app/service/request.service';
import * as qiniu from 'qiniu-js';
import { Observable, Observer } from 'rxjs';
import { API_CONFIG } from 'src/app/service/service.module';
import { fileURLToPath } from 'url';
import { LivelibService } from 'src/app/service/livelib.service';

@Component({
  selector: 'app-vod-lib',
  templateUrl: './vod-lib.component.html',
  styleUrls: ['./vod-lib.component.less']
})
export class VodLibComponent implements OnInit {

  @ViewChild('playUrl', { static: false }) playUrl: ElementRef;
  datalist: any[] | null = null;
  totalCount: number;
  isLoading: boolean = false;
  selectData: any = {
    pageindex: 1,
    pagesize: 10
  };
  categoryName: string = '';
  categoryCover: string = '';
  isEditShow: boolean = false;
  isPlayShow: boolean = false;
  isShareSet: boolean = false;
  data: any = {};
  selectVod: any = {};
  logoUrl: string;
  videoPlayUrl: string;
  categoryId: number;
  ossUrl: string = ossUri;
  qiniuUrl: string = qiniuUri;
  token: string | null = null;
  headers: any | null = null;
  coverUploadUrl: string = this.uri + VOD_CATEGORY_COVER_UPLAOD;
  logoUploadUrl: string = this.uri + VOD_LOGO_UPLOAD;
  uploadStatusText = '上传中，请稍等...';
  taskId: string | null = null;
  interval: any | null = null;
  constructor(
    private requestService: RequestService,
    private msg: NzMessageService,
    private oprationService: OprationService,
    private modalService: NzModalService,
    private route: ActivatedRoute,
    private router: Router,
    private cdf: ChangeDetectorRef,
    private livelibService: LivelibService,
    @Inject(API_CONFIG) private uri: string,
  ) { }

  getlist() {
    this.isLoading = true;
    this.requestService.post(VOD_PAGE, this.selectData).subscribe(result => {
      this.isLoading = false;
      this.totalCount = result['data']['count'];
      this.datalist = result['data']['items'];
      this.datalist.forEach(item => {
        let second = differenceInSeconds(new Date(item['endDate']), new Date(item['startDate']));
        let h = 0;
        let m = 0;
        let s = 0;
        if (second >= 3600) {
          let leftS = second % 3600;
          h = (second - leftS) / 3600;
          second = leftS;
        }
        if (second >= 60) {
          let leftS = second % 60;
          m = (second - leftS) / 60;
          second = leftS;
        }
        s = second;
        let time = [];
        if (h > 0)
          time.push(`${h}小时`)
        if (m > 0)
          time.push(`${m}分`)
        if (s > 0)
          time.push(`${s}秒`)
        item['minute'] = time.join('');
      });
    })
  }

  play(no: number) {
    this.isPlayShow = true;
    let prexUrl = this.datalist[no]['save_supplier'] === 'oss' ? ossUri : qiniuUri;
    this.videoPlayUrl = prexUrl + this.datalist[no]['playUrl'];
  }

  openShareSet(no: number) {
    this.isShareSet = true;
    this.selectVod = this.datalist[no]
    if (!this.selectVod['wxShareTitle']) this.selectVod['wxShareTitle'] = this.selectVod['title']
    if (!this.selectVod['wxShareDesc']) this.selectVod['wxShareDesc'] = this.selectVod['introduce']
    if (!this.selectVod['wxShareCover']) this.selectVod['wxShareCover'] = this.selectVod['logo']
  }
  handlewxCoverChange(info: { file: NzUploadFile }): void {
    switch (info.file.status) {
      case 'uploading':
        this.isLoading = true;
        break;
      case 'done':
        // Get this url from response in real world.
        this.selectVod['wxShareCover'] = info.file.response.name;
        this.isLoading = false;
        break;
      case 'error':
        this.msg.error('Network error');
        this.isLoading = false;
        break;
    }
  }
  updateShare() {
    if (!this.selectVod['wxShareTitle']) {
      this.msg.error("标题不能为空")
      return
    }
    if (!this.selectVod['wxShareDesc']) {
      this.msg.error("标题不能为空")
      return
    }
    if (!this.selectVod['wxShareCover']) {
      this.msg.error("标题不能为空")
      return
    }
    this.requestService.post(VOD_SAVE, {
      id: this.selectVod['id'],
      wxShareCover: this.selectVod['wxShareCover'],
      wxShareDesc: this.selectVod['wxShareDesc'],
      wxShareTitle: this.selectVod['wxShareTitle'],
    }).subscribe(() => {
      this.isShareSet = false
    });
  }
  check(no: number) {
    this.data = this.datalist[no];
    this.videoPlayUrl = ossUri + this.data['playUrl'];
    this.logoUrl = ossUri + this.data['logo'];
    this.isEditShow = true;
  }

  copy() {
    this.playUrl.nativeElement.select();
    document.execCommand('copy');
    this.msg.success('以复制到剪切板');
  }

  editClose() {
    this.isEditShow = false;
  }

  playClose() {
    this.isPlayShow = false;
  }

  delete(id: number) {
    this.modalService.confirm({
      nzTitle: '信息提示',
      nzContent: '确定要删除此视频吗？',
      nzClosable: false,
      nzOnOk: () => {
        this.requestService.delete(VOD_DELETE + id.toString()).subscribe(result => {
          this.oprationService.tips(result, '视频删除成功');
          this.getlist();
        });
      }
    });
  }

  changTitle(index: number) {
    this.requestService.post(VOD_SAVE, { id: this.datalist[index]['id'], title: this.datalist[index]['title'] }).subscribe(result => {

    });
  }

  setMouseOver(index: number, isOver: boolean) {
    this.datalist[index]['isOver'] = isOver;
  }

  deleteCategory() {
    if (this.datalist.length > 0) {
      this.msg.error('请先删除视频库中的视频！');
    } else {
      this.requestService.delete(VOD_CATEGORY_DELETE + this.categoryId.toString()).subscribe(result => {
        if (result['code'] === 'success') {
          this.msg.success('视频库删除成功!')
          this.router.navigateByUrl('/main/vod/category');
        } else {
          this.msg.error(result['data'])
        }
      })
    }
  }

  createNew = async (item: { file: File, onSuccess: any, onProgress: any }) => {
    let that = this;
    if (that.datalist.length > 0 && !that.datalist[0]['id']) {
      that.msg.success('请在视频上传转码完成后再试!');
    }
    if (!this.token) {
      let tokenRes = await this.requestService.get(VOD_UPLOAD_KEY).toPromise();
      this.token = tokenRes['token'];
    }
    if (item.file.type.indexOf('video') == -1) {
      that.msg.success('只能上传视频文件!');
      return;
    }
    let userid = window.sessionStorage['userid'];
    let data = { percent: 0 };
    this.datalist.splice(0, 0, data);
    let name = item.file.name.substring(0, item.file.name.lastIndexOf('.'));
    let key = `VIDEO/${userid}/${item.file.name}`;
    let observable = qiniu.upload(item.file, key, that.token,
      {
        fname: item.file.name,
        mimeType: null
      }, {
      useCdnDomain: true,
      region: qiniu.region.z2
    });
    that.uploadStatusText = '上传中，请稍等...';
    let observer = {
      next(res: any) {
        data['percent'] = parseInt(res['total']['percent']);
        that.cdf.markForCheck();    // 进行标注
        that.cdf.detectChanges();   // 要多加一行这个 执行一次变化检测
        item.onProgress(res['total']);
        // ...
      },
      error(err: any) {
        console.log(err);
        // ...
      },
      complete(res: any) {
        item.onSuccess();
        data['title'] = name;
        that.transerCode(res.key);
      }
    }
    var subscription = observable.subscribe(observer); // 上传开始
  }

  transerCode(key: string) {
    var that = this;
    that.uploadStatusText = '视频转码中请不要跳转其它栏目和关闭页面，请等待转码完成...';
    that.datalist[0]['percent'] = 0;
    that.livelibService.requestApi({ path: '/live/m3u8', method: 'put', data: { key: key } }).subscribe((res: any) => {
      if (res.status === 1) {
        that.taskId = res.taskId;
        that.interval = window.setInterval(that.getTransferCodeProgress, 1000);
      }
      else {
        that.msg.error('提交转码失败');
      }
    });
  }

  getTransferCodeProgress = () => {
    var that = this;
    that.livelibService.requestApi({ path: '/live/m3u8/' + that.taskId, method: 'get' }).subscribe((res: any) => {
      if (res.status === 1) {
        if (that.interval) {
          window.clearInterval(that.interval);
        }
        that.datalist[0]['percent'] = 100;
        that.requestService.post(VOD_SAVE, {
          categoryId: that.categoryId,
          title: that.datalist[0]['title'],
          save_supplier: 'qiniu',
          playUrl: res.key
        }).subscribe((result: any) => {
          Object.assign(that.datalist[0], result['data']);
          that.msg.success('视频转码成功!');
        });
      }
      else {
        if (that.datalist[0]['percent'] < 99) {
          if (that.datalist[0]['percent'] > 95) {
            that.datalist[0]['percent'] = that.datalist[0]['percent'] + 0.1;
          }
          else if (that.datalist[0]['percent'] > 90) {
            that.datalist[0]['percent'] = that.datalist[0]['percent'] + 0.2;
          }
          else if (that.datalist[0]['percent'] > 80) {
            that.datalist[0]['percent'] = that.datalist[0]['percent'] + 0.5;
          }
          else {
            that.datalist[0]['percent'] = that.datalist[0]['percent'] + 1;
          }
        }
      }
    });
  }

  beforeUpload = (file: NzUploadFile, _fileList: NzUploadFile[]) => {
    return new Observable((observer: Observer<boolean>) => {
      const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
      if (!isJpgOrPng) {
        this.msg.error('只能上传图片!');
        observer.complete();
        return;
      }
      const isLt2M = file.size! / 1024 / 1024 < 2;
      if (!isLt2M) {
        this.msg.error('图片必须小于 2MB!');
        observer.complete();
        return;
      }
      observer.next(isJpgOrPng && isLt2M);
      observer.complete();
    });
  };

  handleCategoryChange(info: { file: NzUploadFile }): void {
    switch (info.file.status) {
      case 'uploading':
        this.isLoading = true;
        break;
      case 'done':
        this.requestService.post(VOD_CATEGORY_SAVE, { id: this.categoryId, cover: info.file.response.name }).subscribe(result => {
        });
        this.categoryCover = info.file.response.name;
        this.isLoading = false;
        break;
      case 'error':
        this.msg.error('Network error');
        this.isLoading = false;
        break;
    }
  }

  handleLogoChange(info: { file: NzUploadFile }, index: number): void {
    switch (info.file.status) {
      case 'uploading':
        this.datalist[index]['uploading'] = true;
        this.isLoading = true;
        break;
      case 'done':
        this.requestService.post(VOD_SAVE, { id: this.datalist[index]['id'], logo: info.file.response.name }).subscribe(result => {
        });
        this.datalist[index]['logo'] = info.file.response.name;
        this.isLoading = false;
        this.datalist[index]['uploading'] = false;
        break;
      case 'error':
        this.msg.error('Network error');
        this.isLoading = false;
        this.datalist[index]['uploading'] = false;
        break;
    }
  }

  ngOnInit(): void {
    this.categoryId = Number(this.route.snapshot.params.id);
    this.selectData['categoryId'] = this.categoryId;
    this.requestService.get(VOD_CATEGORY_INFO + this.categoryId).subscribe(result => {
      this.categoryName = result['data']['name'];
      if (result['data']['cover'])
        this.categoryCover = result['data']['cover'];
    })
    this.getlist();
  }

}
